package org.neowei.image.filtering.handle;

import java.awt.image.BufferedImage;

import org.neowei.image.api.ImageOption;
import org.neowei.image.filter.Filter;
import org.neowei.image.filter.FilterOption;
import org.neowei.image.filtering.HorizontalFiltering;
import org.neowei.image.filtering.VerticalFiltering;

public class BGResizeHandle implements IHandle {

	@Override
	public BufferedImage getBufferedImage(ImageOption imageOption, BufferedImage srcimage) {
		int neowidth = imageOption.getNeowidth();
		int neoheight = imageOption.getNeoheight();
		imageOption.setBGFinalWH();
		int finalwidth = imageOption.getFinalwidth();
		int finalheight = imageOption.getFinalheight();
		if (neowidth == 0) {
			neowidth = finalwidth;
			imageOption.setNeowidth(finalwidth);
			return this.doresize(imageOption, srcimage);
		} else if (neoheight == 0) {
			neoheight = finalheight;
			imageOption.setNeoheight(finalheight);
			return this.doresize(imageOption, srcimage);
		} else {
			int halfheight = (neoheight - finalheight) / 2;
			int halfwidth = (neowidth - finalwidth) / 2;
			BufferedImage outimage = new BufferedImage(neowidth, neoheight, BufferedImage.TYPE_INT_RGB);
			for (int x = 0; x < neowidth; x++) {
				for (int y = 0; y < neoheight; y++) {
					outimage.setRGB(x, y, 0x00ffffff);
				}
			}
			BufferedImage inimage = this.doresize(imageOption, srcimage);
			for (int x = halfwidth, i = 0; x < finalwidth + halfwidth; x++, i++) {
				for (int y = halfheight, j = 0; y < finalheight + halfheight - 1; y++, j++) {
					outimage.setRGB(x, y, inimage.getRGB(i, j));
				}
			}
			return outimage;
		}
	}

	private BufferedImage doresize(ImageOption imageOption, BufferedImage srcimage) {
		FilterOption contributor = Filter.getContrib(imageOption.getNeowidth(), imageOption.getSrcwidth());
		return new VerticalFiltering(contributor, imageOption.getSrcheight(), imageOption.getNeowidth(), imageOption.getNeoheight(), new HorizontalFiltering(contributor, imageOption.getSrcwidth(),
				imageOption.getSrcheight(), imageOption.getNeowidth(), srcimage).getBufferedImage()).getBufferedImage();
	}

}
